import { Button, DatePicker, Slider, message } from "antd";
import moment from "moment";
import React, { useCallback, useEffect, useRef, useState } from "react";
import play from "../images/play.png";
import playOff from "../images/playOff.png";
import "../style/DateController.css";
const { RangePicker } = DatePicker;
const timeline = {
  display: "flex",
  position: "absolute",
  bottom: "20px",
  width: "95%",
  background: "rgba(2, 16, 25, 0.7)",
  padding: "10px",
  borderRadius: "4px",
  zIndex: 100,
};

const TimelineController = ({ ChangeSource }) => {
  const ANIMATION_DURATION = 500; // 每次渲染动画持续500ms
  const COUNT = 5; // 每组显示5个日期
  const BATCH_SIZE = 5; // 每次加载5个日期

  const [currentTime, setCurrentTime] = useState(0);
  const [dateRange, setDateRange] = useState();
  const [isPlaying, setIsPlaying] = useState(false);
  const [allDate, setAllDate] = useState([]);
  const [dateTip, setdateTip] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const isPlayingRef = useRef(isPlaying);
  const dataCache = useRef(new Map());
  const loadQueue = useRef([]);
  const isProcessingQueue = useRef(false);
  const currentIndexRef = useRef(0);

  const disabledDate = (current) => {
    return current && current > moment().startOf("day");
  };

  // 简化的数据加载函数
  const loadData = async (date) => {
    if (dataCache.current.has(date)) {
      return dataCache.current.get(date);
    }

    const url = `/data/${date}.json`;
    try {
      const response = await fetch(url, {
        signal: AbortSignal.timeout(5000),
        cache: "force-cache",
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      dataCache.current.set(date, data);
      return data;
    } catch (error) {
      console.error(`Failed to load data for ${date}:`, error);
      return null;
    }
  };

  // 批量加载数据，添加日期检查避免重复请求
  const loadBatch = async (dates) => {
    // 过滤掉已经缓存的日期和正在加载的日期
    const unloadedDates = dates.filter((date) => !dataCache.current.has(date));

    if (unloadedDates.length === 0) return;

    console.log("Loadingbatch:", unloadedDates); 

    // 只取前5个未加载的日期
    const batchDates = unloadedDates.slice(0, BATCH_SIZE);

    for (const date of batchDates) {
      await loadData(date);
    }
  };
  // 处理播放队列
  const processQueue = async () => {
    if (
      isProcessingQueue.current ||
      loadQueue.current.length === 0 ||
      !isPlayingRef.current
    )
      return;

    isProcessingQueue.current = true;
    setIsLoading(true);

    const currentDate = loadQueue.current[0];
    try {
      const data = await loadData(currentDate);
      if (!data) {
        throw new Error("Failed to load data");
      }

      const startTime = Date.now();

      // 更新数据显示
      ChangeSource(data);
      loadQueue.current.shift();
      currentIndexRef.current++;

      // 更新进度条和日期显示
      setCurrentTime((prev) => {
        let newTime = prev + 1;
        if (newTime > COUNT) {
          newTime = 0;
          const nextDates = allDate.slice(
            currentIndexRef.current,
            currentIndexRef.current + COUNT
          );
          setdateTip(nextDates);

          // 预加载下一组数据，但要避免重复加载
          const nextLoadIndex = currentIndexRef.current + COUNT; // 从当前显示的最后一个之后开始
          const nextBatch = allDate.slice(
            nextLoadIndex,
            nextLoadIndex + BATCH_SIZE
          );
          if (nextBatch.length > 0) {
            loadBatch(nextBatch);
          }
        }
        return newTime;
      });

      // 计算剩余动画时间
      const elapsedTime = Date.now() - startTime;
      const remainingTime = Math.max(0, ANIMATION_DURATION - elapsedTime);
      await new Promise((resolve) => setTimeout(resolve, remainingTime));
    } catch (error) {
      message.error(`加载数据失败: ${currentDate}`);
      setIsPlaying(false);
    } finally {
      setIsLoading(false);
      isProcessingQueue.current = false;

      if (loadQueue.current.length > 0 && isPlayingRef.current) {
        processQueue();
      } else if (loadQueue.current.length === 0) {
        setIsPlaying(false);
        setCurrentTime(0);
        currentIndexRef.current = 0;
        setdateTip(allDate.slice(0, COUNT));
      }
    }
  };

  useEffect(() => {
    isPlayingRef.current = isPlaying;

    if (isPlaying) {
      loadQueue.current = allDate.slice(currentIndexRef.current);
      processQueue();
    }
  }, [isPlaying, allDate]);

  const togglePlay = () => {
    if (allDate.length < 1) {
      message.warning("请选择日期");
      return;
    }
    setIsPlaying((prevIsPlaying) => !prevIsPlaying);
  };

  // 修改日期选择处理，优化初始加载
  const handleDateChange = async (dateStrings) => {
    if (!dateStrings) {
      setdateTip([]);
      setAllDate([]);
      setCurrentTime(0);
      currentIndexRef.current = 0;
      dataCache.current.clear();
      return;
    }

    setDateRange(dateStrings);
    const dates = getDatesBetween(dateStrings[0], dateStrings[1]);
    setAllDate(dates);
    setdateTip(dates.slice(0, COUNT));
    setCurrentTime(0);
    currentIndexRef.current = 0;

    // 加载第一组数据和预加载第二组数据
    if (dates.length > 0) {
      setIsLoading(true);
      try {
        // 加载前10个日期（当前显示的5个和下一组5个）
        await loadBatch(dates.slice(0, BATCH_SIZE * 2));
      } finally {
        setIsLoading(false);
      }
    }
  };

  const getDatesBetween = useCallback((startDateStr, endDateStr) => {
    const startDate = new Date(startDateStr);
    const endDate = new Date(endDateStr);
    if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
      return [];
    }
    const dates = [];
    let currentDate = new Date(startDate);
    while (currentDate <= endDate) {
      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, "0");
      const day = String(currentDate.getDate()).padStart(2, "0");
      dates.push(`${year}-${month}-${day}`);
      currentDate.setDate(currentDate.getDate() + 1);
    }
    return dates;
  }, []);

  return (
    <div className="timeline-controller" style={timeline}>
      <div
        className="control-buttons"
        style={{ width: "25%", display: "flex", alignItems: "center" }}
      >
        <RangePicker
          disabledDate={disabledDate}
          allowClear={true}
          onChange={handleDateChange}
          format="YYYY-MM-DD"
          value={dateRange}
        />
        <Button
          onClick={togglePlay}
          style={{
            marginLeft: "5px",
            marginRight: "5px",
            height: "0px",
            width: "0px",
            borderColor: "transparent",
            border: "none",
          }}
          loading={isLoading}
        >
          <img src={!isPlaying ? play : playOff} alt=""  />
        </Button>
      </div>
      <div style={{ width: "70%" }}>
        <div
          style={{
            position: "absolute",
            zIndex: 100,
            display: "flex",
            justifyContent: "space-around",
            width: "70%",
          }}
        >
          {dateTip &&
            dateTip.map((item, index) => (
              <div key={index} style={{ color: "#fff", marginLeft: "20px" }}>
                {item}
              </div>
            ))}
        </div>
        <Slider
          value={currentTime}
          onChange={(value) => setCurrentTime(value)}
          min={0}
          max={dateTip.length}
          step={1}
        />
      </div>
    </div>
  );
};

export default TimelineController;
